package com.situ.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.situ.web.entity.User;

public class LoginFilter implements Filter{

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		System.out.println("LgoinFilter.doFilter()");
	     //判断有没有登录
	     //1、如果没有登录，重定向到登录界面
	     HttpServletRequest httpServletRequest = (HttpServletRequest) request;
	     HttpServletResponse httpServletResponse = (HttpServletResponse) response;
	     String uri = httpServletRequest.getRequestURI();
	     System.out.println("uri: " + uri);
	     String servletPath = httpServletRequest.getServletPath();
	     System.out.println("servletPath: " + servletPath);
	     
	     //从Session看一下这个用户有没有登录
	     HttpSession session = httpServletRequest.getSession();
	     User user = (User) session.getAttribute("user");
	     // 特殊请求不需要验证是否登录
	     if ("/login.jsp".equals(servletPath)
	          || "/login".equals(servletPath)) {
	        chain.doFilter(request, response);
	     } else {
	        if (user == null) {
	          // 用户没有登录，重定向到登录界面
	          httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/login.jsp");
	          return;
	        }
	        // 2、如果登录上，chain.doFilter()
	        chain.doFilter(httpServletRequest, httpServletResponse);
	     }
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}
	

}
